package at.fhooe.obd.gui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import at.fhooe.obd.tasks.GetTrackByIdTask;
import at.fhooe.obd.tasks.GetTracksForUserTask;

public class DisplayTrackActivity extends Activity implements OnItemClickListener
{

	String trackID = null;
	
	String[] trackInfo = null;
	
	Map<String, List<Double>> doubleValueMap = new HashMap<String, List<Double>>();
	Map<String, List<String>> stringValueMap = new HashMap<String, List<String>>();
	
	Map<String, String> labelNameMap = new HashMap<String, String>();
	// This is some dirty shit, but I am not in the mood to think at 2:42
	Map<String, String> backMap = new HashMap<String, String>();
	
	List<String> allLabels = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_track);
		
		initLabelNames();
		trackID = (String)getIntent().getExtras().getString(Keys.JSON_TRACK_ID);
		
		GetTrackByIdTask getTrackById = new GetTrackByIdTask(this);
		getTrackById.execute(trackID);
	}
	
	private void initLabelNames()
	{
		labelNameMap.put(Keys.JSON_LATITUDE, "Latitude");
		labelNameMap.put(Keys.JSON_LONGITUDE, "Longitude");
		labelNameMap.put(Keys.JSON_ALTITUDE, "Altitude");
		labelNameMap.put(Keys.JSON_FUEL_CONSUMPTION, "Fuel Consumption");
		labelNameMap.put(Keys.JSON_SPEED, "Vecihle Speed");
		labelNameMap.put(Keys.JSON_ENGINE_LOAD, "Engine Load");
		labelNameMap.put(Keys.JSON_ENGINE_COOLENT_TEMP, "Engine Coolant Temperature");
		labelNameMap.put(Keys.JSON_ENGINE_RUNTIME, "Engine Runtime");
		labelNameMap.put(Keys.JSON_AIR_TEMP, "Air Temperature");
		labelNameMap.put(Keys.JSON_OIL_TEMP, "Oil Temperature");
		labelNameMap.put(Keys.JSON_FUEL_RATE, "Fuel Rate");
		labelNameMap.put(Keys.JSON_CONTOL_MODULE_VOLTAGE, "Control Module Voltage");
		labelNameMap.put(Keys.JSON_TIME, "Time");
		labelNameMap.put(Keys.POSITION, "Positions Travelled");
		labelNameMap.put(Keys.TRACK_INFO, "Track Information");
		
		for (Entry<String, String> entry : labelNameMap.entrySet())
		{
			backMap.put(entry.getValue(), entry.getKey());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_display_track, menu);
		return true;
	}
	
	public void setDoubleMap(Map<String, List<Double>> doubleValueMap)
	{
		this.doubleValueMap = doubleValueMap;
	}
	
	public void setStringMap(Map<String, List<String>> stringValueMap)
	{
		this.stringValueMap =  stringValueMap;
	}
	
	private void addListItems()
	{
		String [] labels = new String[allLabels.size() + 2];
		labels[0] = labelNameMap.get(Keys.TRACK_INFO);
		labels[1] = labelNameMap.get(Keys.POSITION);
		
		int i = 2;
		for (String l : allLabels)
		{
			if (this.labelNameMap.containsKey(l))
				labels[i] = labelNameMap.get(l);
			else
				labels[i] = l;
			i++;
		}
		
		ListView lv = (ListView) findViewById(R.id.lv_track);
		lv.setOnItemClickListener(this);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_list_item_1,
				labels);

		lv.setAdapter(adapter);
	}
	
	public void setAllLabels(List<String> allLabels)
	{
		this.allLabels = allLabels;
		addListItems();
	}

	private TimeSeries getTimeSeries(String name, double[] xVals, double[] yVals)
	{
		if (xVals.length != yVals.length)
		{
			Log.e("", "The time series values must have the same lenght");
		}
		
		TimeSeries series = new TimeSeries(name); 
		for( int i = 0; i < xVals.length; i++)
		{
			series.add(xVals[i], yVals[i]);
		}
		
		return series;
	}
	
	public void setTrackInfo(String userName, 
			String car, String horsepowers, String date)
	{
		this.trackInfo = new String [] {
				"User: " + userName,
				"Date: " + date,
				"Car Name : " + car,
				"Car Horse Power: " + horsepowers, 
				};
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View lv, int arg2, long arg3)
	{
		if (lv instanceof TextView)
		{
			TextView tv = (TextView)lv;
			
			String text = tv.getText().toString();
			String key = null;
			
			// map back from label to key...
			if (backMap.containsKey(text))
				key = backMap.get(text);
			else
				key = text;
			
			if (doubleValueMap.containsKey(key))
			{
				double[] xVals = new double[doubleValueMap.get(key).size()];
				double[] yVals = new double[doubleValueMap.get(key).size()];
				
				for (int i = 0; i < doubleValueMap.get(key).size(); i++)
				{
					xVals[i] = i + 1;
					yVals[i] = doubleValueMap.get(key).get(i);
				}
				
				// prepare the data for graph
				List<TimeSeries> timeSeries = new ArrayList<TimeSeries>();
				TimeSeries series = getTimeSeries(text, xVals, yVals);
				timeSeries.add(series);
				
				List<Integer> colors = new ArrayList<Integer>();
				colors.add(Color.YELLOW);
				
				List<PointStyle> styles = new ArrayList<PointStyle>();
				styles.add(PointStyle.DIAMOND);
				
				LineGraph lineGrap = new LineGraph();
				
				Intent lineIntent = lineGrap.getIntent(this, timeSeries, colors,
						styles, text, false);
				startActivity(lineIntent);
			}
			
			if (key.equals(Keys.POSITION))
			{
				// handle position here...
				Intent intent = new Intent(this, PositionActivity.class);
				intent.putExtra(Keys.JSON_LONGITUDE, stringValueMap.get(Keys.JSON_LONGITUDE).toArray(new String[0]));
				intent.putExtra(Keys.JSON_LATITUDE, stringValueMap.get(Keys.JSON_LATITUDE).toArray(new String[0]));
				intent.putExtra(Keys.JSON_ALTITUDE, stringValueMap.get(Keys.JSON_ALTITUDE).toArray(new String[0]));
				this.startActivity(intent);
				
			}
			
			if (key.equals(Keys.TRACK_INFO) && this.trackInfo != null)
			{
				Intent intent = new Intent(this, TrackInfoActivity.class);
				intent.putExtra(Keys.TRACK_INFO, this.trackInfo);
				this.startActivity(intent);
			}
		}
		
	}
}
